package com.ling.luo.trade.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.ling.luo.trade.config.AlipayConfig;
import com.ling.luo.trade.service.AlipayService;
import com.ling.luo.trade.utils.AmountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝-统一收单交易支付接口
 *
 * @author luohoujian
 * @date 2021/04/27
 */
@Slf4j
@Service
public class AlipayTradePayServiceImpl implements AlipayService {

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public String alipayTrade() {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId()
                , alipayConfig.getMerchantPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset()
                , alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
        AlipayTradePayRequest request = new AlipayTradePayRequest();

        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", "B" + System.currentTimeMillis());
        map.put("scene", "bar_code");
        // todo 获取支付宝授权码 auth_code
        //map.put("auth_code", "");
        map.put("product_code", "FACE_TO_FACE_PAYMENT");
        map.put("subject", "统一收单支付测试");
        map.put("total_amount", AmountUtil.fenToYuan(1000L));
        map.put("discountable_amount", AmountUtil.fenToYuan(10L));
        map.put("trans_currency", "CNY");
        map.put("settle_currency", "CNY");
        map.put("body", "支付宝统一收单支付交易接口测试-使用场景：收营员使用扫描设备读取用户信息");

        String jsonStr = JSONObject.toJSONString(map);
        log.info("支付宝-统一收单交易支付接口BizContent入参[{}]", jsonStr);
        request.setBizContent(jsonStr);
        AlipayTradePayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("支付宝-统一收单交易支付接口响应数据body[{}]", response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

}
